#include "ACommunicator.hpp"
#include	"TcpUnix.hpp"
#include	"TcpWin.hpp"

ACommunicator::ACommunicator(int port)
  :
#ifdef			__unix__
  Tcp(new TcpUnix()),
#else
  Tcp(new TcpWin()),
#endif
    Port(port)
{
}

int ACommunicator::CheckIsComplete(Connected &co,
				   int fd)
{
  int                   bufferSize;
  int                   alreadyRead;

  bufferSize = co.GetReadBuf().GetBufferSize();
  alreadyRead = co.GetReadBuf().GetAlreadyRead();
  if (bufferSize == alreadyRead)
    {
      Ctl.SetVal(Control::BUF_COMPLETE);
      Ctl.GetBuf().SetBuffer(co.GetReadBuf().GetBuffer());
      Ctl.GetBuf().SetBufferSize(bufferSize);
      Ctl.GetBuf().SetAlreadyRead(alreadyRead);
      Ctl.SetFd(fd);
      co.GetReadBuf().SetBuffer(NULL);
      co.GetReadBuf().SetAlreadyRead(-1);
      co.GetReadBuf().SetBufferSize(0);
      return (0);
    }
  return (-1);
}

ACommunicator::~ACommunicator()
{
}

int	ACommunicator::TryToWrite(std::list<Buffer *>	&writeBuf,
				  int			fd)
{
  std::list<Buffer *>::iterator	it;
  Buffer	*buf;
  int		ret;
  
  it = writeBuf.begin();
  if (!writeBuf.empty())
    {
      if ((ret = Tcp->NetWrite(fd, *(*it))) == -1)
	return (-1);
      else if (ret == 1)
	{
 	  buf = (*it);
	  if (buf->GetAlreadyRead() == buf->GetBufferSize())
	    {
	      delete[] writeBuf.front()->GetBuffer();
	      writeBuf.pop_front();
	      return (0);
	    }
	}
      else if (ret == 0)
	{
	  Ctl.SetVal(Control::DISCONNECTED);
	  return (0);
	}
    }
  return (1);
}

int	ACommunicator::TryToRead(Buffer	&readBuf,
				 int	fd)
{
  int		ret;

  if ((ret = Tcp->NetRead(fd, readBuf)) == -1)
    {
      Ctl.SetFd(fd);
      Ctl.SetVal(Control::DISCONNECTED);
      return (0);
    }
  else if (ret == 0)
    {
      Ctl.SetFd(fd);
      Ctl.SetVal(Control::DISCONNECTED);
      return (0);
    }
  return (1);
}

int ACommunicator::TraitementBuf()
{
  printf("buffer size = %d, buffer = %s\n", Ctl.GetBuf().GetBufferSize(), Ctl.GetBuf().GetBuffer());
  return (0);
}

